package top.xxyu.config;


import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import top.xxyu.entity.MailMessage;
import top.xxyu.entity.UserMail;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * 发送邮件
 */
@Slf4j
public class SendEmail {

    public static void main(String[] args) {


        // 收件人电子邮箱
        String to = "643816900@qq.com";

        // 发件人电子邮箱
        String from = "jx@xxyu.top";
        String password = "d-i5)W;vlNczpw~T%nb3?x87>";

        // 指定发送邮件的主机为 localhost
        String host = "smtp.qiye.aliyun.com";
        String protocol = "smtp";
        String subject = "hell";
        String context = "context";
        send(subject, context, to, from, password, host);

    }


    /**
     * 发送邮件没有附件
     *
     * @param subject
     * @param context
     * @param toUser
     * @param user
     * @param password
     * @param mailServiceHost
     */
    public static void send(String subject, String context, String toUser, String user, String password, String mailServiceHost) {
        try {
            send(subject, context, toUser, user, password, mailServiceHost, "", "");
        } catch (GeneralSecurityException e) {
            log.info("发送邮件失败 " + user + "----->" + toUser);
            e.printStackTrace();

        }
    }

    /**
     * 发送邮件带附件
     *
     * @param subject         主题
     * @param context         邮件内容
     * @param toUser          接收人
     * @param user            发送人
     * @param password        密码
     * @param mailServiceHost 邮箱服务器
     * @param filepath        文件路径
     */
    public static void send(String subject, String context, String toUser, String user, String password, String mailServiceHost, String filepath) {
        try {
            send(subject, context, toUser, user, password, mailServiceHost, filepath, "");
        } catch (GeneralSecurityException e) {
            log.info("发送邮件失败 " + user + "----->" + toUser);
            e.printStackTrace();

        }
    }

    /**
     * 发送邮件 需要协议
     *
     * @throws GeneralSecurityException
     */
    public static boolean send(MailMessage mailMessage) {
        boolean success = true;
        UserMail mailInfo = mailMessage.getFromUserMail();
        String subject = mailMessage.getSubject();
        String context = mailMessage.getContext();
        String filepath = mailMessage.getFilepath();
        String toUser = mailMessage.getToUser();
        String user = mailInfo.getUserMail();
        String password = mailInfo.getPassword();
        String mailServiceHost = mailInfo.getMailServiceHost();
        String protocol = mailInfo.getProtocol();
        try {
            send(subject, context, toUser, user, password, mailServiceHost, filepath, protocol);
        } catch (GeneralSecurityException e) {
            log.info("邮件发送失败----------" + mailMessage);
            success = false;
            e.printStackTrace();
        }
        return success;
    }

    /**
     * 发送邮件 需要协议
     *
     * @param subject
     * @param context
     * @param toUser
     * @param user
     * @param password
     * @param mailServiceHost 邮箱服务器
     * @param filepath 文件路径
     * @param protocol 发送协议
     * @throws GeneralSecurityException
     */
    public static void send(String subject, String context, String toUser, String user, String password, String mailServiceHost, String filepath, String protocol) throws GeneralSecurityException {
        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.host", mailServiceHost);
        // 发送邮件协议名称
        properties.setProperty("mail.transport.protocol", StringUtils.isEmpty(protocol) ? "smtp" : protocol);

        // 开启debug调试
        properties.setProperty("mail.debug", "true");

        properties.put("mail.smtp.auth", "true");
        properties.setProperty("mail.user", user);
        properties.setProperty("mail.password", password);


        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        // 获取默认的 Session 对象。
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password); //发件人邮件用户名、密码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象。
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(user));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toUser));

            // Set Subject: 头字段
            message.setSubject(subject);

            // 创建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
            messageBodyPart.setText(context);

            // 创建多重消息
            Multipart multipart = new MimeMultipart();

            // 设置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            // 附件部分
//            String filepath = "C:\\Users\\Admin\\Desktop\\手机个税.doc";
            File file = new File(filepath);
            if (file.exists()) {
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filepath);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(file.getName());
                multipart.addBodyPart(messageBodyPart);

            }
            // 发送完整消息
            message.setContent(multipart);

            //   发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }

}
